import { createAction } from 'redux-actions';
import * as types from '../constants/ActionTypes';
import * as homeService from '../services/homeService';
import * as topicService from '../services/topicService';

export const getZones = createAction(types.GET_ZONES, async () => {
  try {
    const zones = await homeService.getZones();
    let { 0: selectedZone } = zones;
    if (!selectedZone) selectedZone = {};
    let { 0: selectedMenu } = selectedZone.menus ? selectedZone.menus : [];
    if (!selectedMenu) selectedMenu = {};
    let { 0: selectedSubmenu } = selectedMenu.submenus ? selectedMenu.submenus : [];
    if (!selectedSubmenu) selectedSubmenu = {};

    const topics = await topicService.getTopics(selectedZone._id, selectedMenu.key, selectedMenu.key);

    const data = {
      selectedZone,
      selectedMenu,
      selectedSubmenu,
      zones,
      topics,
    };

    return data;
  } catch (err) {
    console.log(err);
  }
});

export const updateMenu = createAction(types.UPDATE_MENU, (selectedMenuKey, selectedSubmenuKey) => ({
  selectedMenuKey,
  selectedSubmenuKey,
}));
